package com.farm.wcp.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

import com.farm.file.util.ViewDirUtils;
import com.farm.parameter.FarmParameterService;
import net.coobird.thumbnailator.Thumbnails;

public class ThumbnailsUtils {

	
	public static int getAbleWidth(String towidth) {
		int ableWidht = 0;
		int differenceInt = 1000000;
		for (String width : FarmParameterService.getInstance()
				.getParameterStringList("config.doc.img.thumbnails.width")) {
			int widthInt = Integer.valueOf(width);
			int towidthInt = Integer.valueOf(towidth);
			int cdifferenceInt = Math.abs(towidthInt - widthInt);
			if (cdifferenceInt < differenceInt) {
				differenceInt = cdifferenceInt;
				ableWidht = widthInt;
			}
		}
		return ableWidht;
	}

	
	public static File trimImg(String exname, String towidth, File file, File newfile) throws IOException {
		int towidthInt = getAbleWidth(towidth);
		if (towidthInt <= 0) {
			return file;
		}
		// 生成缩略图
		// 文件后缀名
		if (exname == null || exname.trim().isEmpty()) {
			throw new RuntimeException("exname is not exist!");
		}
		if (newfile == null) {
			newfile = getFormatImg(file, towidthInt, exname);
		}
		// 判断图片是否已经存在了
		if (!newfile.exists()) {
			if (file.getPath().indexOf(newfile.getName()) > 0) {
				return file;
			}
			// 不存在则直接变换
			BufferedImage bufferedImage = ImageIO.read(file);
			if (bufferedImage == null) {
				throw new IOException("the file is not exist:");
			}
			int cwidth = bufferedImage.getWidth();
			if (towidthInt > cwidth) {
				towidthInt = cwidth;
			}
			if (!newfile.getParentFile().exists()) {
				newfile.getParentFile().mkdirs();
			}
			Thumbnails.of(file).width(towidthInt).toFile(newfile);
		}
		return newfile;
	}

	
	public static File getFormatImg(File file, int width, String prefix) {
		File viewDir = new File(ViewDirUtils.getPath(file));
		viewDir.mkdirs();
		String plusName = "THUMBNAILS." + width + "." + prefix;
		return new File(viewDir.getPath() + File.separator + "thumbnail" + File.separator + plusName);
	}
}
